from rest_framework import serializers

from goods.serializers import GoodsSerialzier
from orders.models import OrderModel, OrderGoodsModel


class OrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderModel
        fields = '__all__'

    def to_representation(self, instance):
        # instance为订单对象
        data = super().to_representation(instance)

        # order_goods = OrderGoodsModel.objects.filter(order=instance).all()
        order_goods = instance.ordergoodsmodel_set.all()

        result = []
        total = 0
        for order_good in order_goods:
            goods = {
                'o_goods': GoodsSerialzier(order_good.goods).data
            }
            result.append(goods)
            # 计算总价
            total += order_good.goods.marketprice * order_good.goods_num

        data['order_goods_info'] = result
        data['o_price'] = total
        return data
